<?php

namespace App\Services\Admin\Version;

use App\Exceptions\AdminException;
use App\Services\BaseService;
use App\Managers\Admin\Version\VersionManager;

class VersionService extends BaseService
{
    public function __construct(VersionManager $manager)
    {
        parent::__construct();
        $this->manager = $manager;
    }

    public function getVersion()
    {
        return $this->manager->getVersion();
    }

    public function getUpdatePackage()
    {
        $zipDirectory = public_path('zip');

        // 检查目录是否存在
        if (!is_dir($zipDirectory)) {
            throw new AdminException('zip目录不存在');
        }

        // 获取所有zip文件
        $files = glob($zipDirectory . '/*.zip');

        if (empty($files)) {
            throw new AdminException('zip目录中没有找到文件');
        }

        // 按修改时间排序，获取最新的文件
        usort($files, function($a, $b) {
            return filemtime($b) - filemtime($a);
        });

        $latestFile = $files[0];

        // 获取相对路径用于URL生成
        $relativePath = str_replace(public_path(), '', $latestFile);
        $relativePath = ltrim(str_replace('\\', '/', $relativePath), '/');

        return [
            'file_path' => $relativePath,
            'download_url' => url($relativePath),
            'file_name' => basename($latestFile),
            'file_size' => round(filesize($latestFile) / (1024 * 1024), 2) . ' MB',
            'modified_time' => date('Y-m-d H:i:s', filemtime($latestFile))
        ];
    }
}
